package com.shengtsource.minicat.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 静态资源工具类
 * @author shengtsource
 */
public class StaticResourceUtils {
    /**
     * 获取静态资源真实路径
     * @param path
     * @return
     */
    public static String getRealPath(String path){
        String rootPath = StaticResourceUtils.class.getResource("/").getPath();
        return rootPath.concat(path).replaceAll("\\\\", File.separator);
    }

    /**
     * 输出静态资源文件
     * @param fileInputStream
     * @param outputStream
     */
    public static void outputStaticResource(FileInputStream fileInputStream, OutputStream outputStream) throws IOException {

        int responseSize = 0;
        if(responseSize == 0) {
            responseSize = fileInputStream.available();
        }

        //写出缓存
        int byteSize = 1024;
        byte[] bytes = new byte[byteSize];
        int written = 0;
        //输出响应头
        outputStream.write(HttpProtocolUtils.getResponseHeader200(responseSize).getBytes());
        //输出响应体
        while (written < responseSize) {
            // 剩余数据长度小于1024
            if(written + byteSize > responseSize) {
                byteSize = responseSize - written;
                bytes = new byte[byteSize];
            }

            fileInputStream.read(bytes);
            outputStream.write(bytes);

            outputStream.flush();
            written += byteSize;
        }
    }
}
